//
//  ONTabbarViewController.m
//  Volatix
//
//  Created by Familly on 6/11/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "ONTabbarViewController.h"

@interface ONTabbarViewController ()<NSURLConnectionDelegate>
@end

@implementation ONTabbarViewController
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    _isLeftBackButton=NO;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        [self getListScreen];
        // perform main thread operation
        dispatch_sync(dispatch_get_main_queue(), ^{
            
        });
    });
    
    // recieve message request to server
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestServerUpdateRealTime:) name:UPDATE_REAL_TIME object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestServerUpdateDayAhead:) name:UPDATE_DAY_AHEAD object:nil];
    
    
}
#pragma mark - Helper Method

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}

-(void)requestServerUpdateDayAhead:(NSNotification *)notification
{
    NSMutableArray *dicArray =(NSMutableArray *)[notification object];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        [self requestDataDayAheadByArray:dicArray];
        // perform main thread operation
        dispatch_sync(dispatch_get_main_queue(), ^{
            
        });
    });

}


-(void)requestServerUpdateRealTime:(NSNotification *)notification
{
    NSLog(@"%s",__FUNCTION__);
    NSMutableArray *dicArray =(NSMutableArray *)[notification object];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        ///[self requestDataUpdateByArray:dicArray];
        [self requestDataUpdateRealtimeByArray:dicArray];
        // perform main thread operation
        dispatch_sync(dispatch_get_main_queue(), ^{
            
        });
    });
}
-(void)getListScreen
{
    _arrRealTimeResult =[[NSMutableArray alloc] init];
    _arrDayAheadResult =[[NSMutableArray alloc] init];
    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_GET_LIST_DYNAMIC_COLUMN andPostMethodKind:enumAPIRequestMethod_GET andParams:nil andString:nil inView:nil completeBlock:^(id responseObject) {
        NSDictionary * item =[Utils objectForKeyNotNull:@"objects" andDictionnary:responseObject];//
        if(item!=nil)
        {
            for(NSDictionary *_child in item)
            {
                NSDictionary * _baby =[Utils objectForKeyNotNull:@"screenColumns" andDictionnary:_child];
                if(_baby!=nil)
                {
                    
                    for (NSDictionary *childBaby in _baby ) {
                        ONObjectColumn *objectColumn =[ONObjectColumn modelObjectWithDictionary:childBaby];
                        if(objectColumn!=nil)
                        {
                           // NSLog(@" screenName %@ - Column %@ ",objectColumn.screenName,objectColumn.nameColumn);
                            if([objectColumn.screenName isEqualToString:@"Realtime"])
                            {
                                [_arrRealTimeResult addObject:objectColumn];
                            }
                            else if([objectColumn.screenName isEqualToString:@"DayAhead"])
                            {
                                [_arrDayAheadResult addObject:objectColumn];
                            }
                        }
                        
                    }
                }
            }
        }
        [self.tabbarDelegateDayAhead updateColumnNameDayAHead:_arrDayAheadResult];
        /// Update for Real Time Screen
        [self.tabbarDelegateRealTime updateColumnName:_arrRealTimeResult];
        
    } failureBlock:^(NSError *error) {
        //
    }];
}
-(void)requestDataDayAheadByArray:(NSMutableArray *)dicArray
{
    if(dicArray==nil||[dicArray count]==0){return;}
    NSMutableArray *arr = [NSMutableArray array];
    for (int index=0;index<[dicArray count]; index++) {
        ONISOObjects *anObject = (ONISOObjects *)[dicArray objectAtIndex:index];
        // NSLog(@"%@ - %@ ",anObject.iso,anObject.name);
        NSArray *_objects;
        switch (anObject.type) {
            case LEVEL_ISO:
                _objects = [NSArray arrayWithObjects:anObject.name , @"", @"", nil];
                break;
            case LEVEL_LOADZONE:
                _objects = [NSArray arrayWithObjects:anObject.iso ,anObject.name, @"", nil];
                break;
            case LEVEL_POWERPOINT:
                _objects = [NSArray arrayWithObjects:anObject.iso ,anObject.loadZone,anObject.name, nil];
                break;
            default:
                break;
        }
        NSArray *keys = [NSArray arrayWithObjects:@"iso", @"loadZone", @"powerpoint", nil];
        NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:_objects forKeys:keys];
        [arr addObject:questionDict];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr
                                                       options:(NSJSONWritingOptions) (NSJSONWritingPrettyPrinted)
                                                         error:nil];
    NSString *body = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   
    NSDate *currDate=[NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    //NSLog(@"%@",dateString);
    //dateString=[dateString stringByReplacingOccurrencesOfString:@" " withString:@"%"];
   // NSLog(@"Current %@",dateString);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:/*@"2014-06-17%201:00:00"*/dateString  forKey:@"DATE_TIME"];
    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_UPDATE_DATA_DAY_AHEAD andPostMethodKind:enumAPIRequestMethod_POST_ARRAY andParams:params andString:body inView:nil completeBlock:^(id responseObject) {
        ///
        NSMutableArray *arrayResult=[[NSMutableArray alloc] init];
        for(NSDictionary *item in [responseObject allValues]) {
            ONObjectDayAhead *_obj=[ONObjectDayAhead modelObjectWithDictionary:item];
            if(_obj!=nil)
            {
                //NSLog(@"HE %8.3f",_obj.hourending);
                [arrayResult addObject:_obj];
            }
        
        }
        
        
        
        [self.tabbarDelegateDayAhead updateDataDayAhead:arrayResult];
    } failureBlock:^(NSError *error) {
        ///
    }];
    
    
    
    
}
-(void)requestDataUpdateRealtimeByArray:(NSMutableArray *)dicArray
{
     if(dicArray==nil||[dicArray count]==0){return;}
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int index=0;index<[dicArray count]; index++) {
        ONISOObjects *anObject = (ONISOObjects *)[dicArray objectAtIndex:index];
        // NSLog(@"%@ - %@ ",anObject.iso,anObject.name);
        NSArray *_objects=nil;
        switch (anObject.type) {
            case LEVEL_ISO:
                _objects = [NSArray arrayWithObjects:anObject.name , @"", @"", nil];
                break;
            case LEVEL_LOADZONE:
                _objects = [NSArray arrayWithObjects:anObject.iso ,anObject.name, @"", nil];
                break;
            case LEVEL_POWERPOINT:
                _objects = [NSArray arrayWithObjects:anObject.iso ,anObject.loadZone,anObject.name, nil];
                break;
            default:
                break;
        }
        NSArray *keys = [NSArray arrayWithObjects:@"iso", @"loadZone", @"powerpoint", nil];
        if(_objects!=nil&&[_objects count]>0)
        {
            NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:_objects forKeys:keys];
            [arr addObject:questionDict];
        }
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr
                                                       options:(NSJSONWritingOptions) (NSJSONWritingPrettyPrinted)
                                                         error:nil];
    NSString *body = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   // NSLog(@"******** request--------- %@ ", body);
    [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_UPDATE_DATA_REAL_TIME andPostMethodKind:enumAPIRequestMethod_POST_ARRAY andParams:nil andString:body inView:nil completeBlock:^(id responseObject) {
        
        //NSLog(@"******** jsonResponse--------- %@ ********", responseObject);
        NSMutableArray *arrayResult=[[NSMutableArray alloc] init];
        for(NSDictionary *item in [responseObject allValues]) {
            ONObjectRealTime *_obj=[ONObjectRealTime modelObjectWithDictionary:item];
            if(_obj!=nil)
            {
                //NSLog(@"dailyHigh %8.3f",_obj.dailyHigh);
                [arrayResult addObject:_obj];
            }
            
        }
        
        [self.tabbarDelegateRealTime updateDataRealtime:arrayResult];
        
    } failureBlock:^(NSError *error) {
            NSLog(@" ********    ERROR--------- %@ ********", error);
    }];

}

- (IBAction)clickLeftItemBar:(id)sender {
    
    if(_isLeftBackButton)
    {
        
        if(self.tabbarDelegateDayAhead_Detail!=nil)
        {
            [self.tabbarDelegateDayAhead_Detail backToScreen:sender];
        }
    }
    else
    {
    
        if(self.tabbarDelegateRealTime!=nil)
        {
            [self.tabbarDelegateRealTime ONLeftItemselected:sender];
        }
    }
    
    
}
- (IBAction)clickRightItemBar:(id)sender {
    
    if(self.tabbarDelegateRealTime!=nil)
    {
        [self.tabbarDelegateRealTime ONRightItemselected:sender];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UPDATE_REAL_TIME object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UPDATE_DAY_AHEAD object:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 */
@end
